﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _7.ReplaceWordSubstring
{
    class ReplaceWord
    {
        static void Main(string[] args)
        {
            StreamReader reader = new StreamReader(@"..\..\ReplaceWord.cs");
            StreamWriter writer = new StreamWriter(@"..\..\Replaced.txt");
            StringBuilder result = new StringBuilder();
            using (writer)
            {
                using (reader)
                {
                    while (reader.EndOfStream != true)
                    {
                        string line = reader.ReadLine();
                        int startIndex = 0;
                        int indexOfStart = line.IndexOf("start", StringComparison.OrdinalIgnoreCase);
                        if (indexOfStart < 0)
                        {
                            result.Append(line);
                        }
                        else
                        {
                            while (indexOfStart >= 0)
                            {
                                string subStr = line.Substring(startIndex, indexOfStart - startIndex);
                                startIndex = indexOfStart + 5;
                                indexOfStart = line.IndexOf("start", startIndex, StringComparison.OrdinalIgnoreCase);
                                result.Append(subStr);
                                result.Append("finish");
                            }
                            int lastIndexOfStart = line.LastIndexOf("start", StringComparison.OrdinalIgnoreCase);
                            string lastSubstring = line.Substring(lastIndexOfStart + 5);
                            result.Append(lastSubstring);
                        }
                        writer.WriteLine(result.ToString());
                        //finish finish finish finish finish finish finish finish finish finish finish finish 
                        //start start start start start start start start start start start start start start 
                        result.Clear();
                        writer.Flush();
                    }
                }
            }
        }
    }
}
